package com.roger.tool.utils;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.text.TextUtils;

public class AppInfoUtil {

	public static String getAppName(Context pContext) {

		String appName = null;

		if (pContext != null) {
			try {
				PackageInfo pkg = pContext.getPackageManager().getPackageInfo(pContext.getPackageName(), 0);
				appName = pkg.applicationInfo.loadLabel(pContext.getPackageManager()).toString();
			} catch (Exception e) {

			}
		}
		if (TextUtils.isEmpty(appName)) {
			appName = "unknown";
		}
		return appName;
	}

	/**
	 * 获取应用程序版本名称信息
	 * 
	 * @param context
	 * @return 当前应用的版本名称
	 */
	public static String getVersionName(Context context) {

		String versionName = null;

		if (context != null) {
			try {
				PackageManager packageManager = context.getPackageManager();
				PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
				versionName = packageInfo.versionName;

			} catch (NameNotFoundException e) {

			}
		}
		if (TextUtils.isEmpty(versionName)) {
			versionName = "unknown";
		}
		return versionName;
	}

	public static int getVersionCode(Context context) {
		int versionCode = 0;
		try {
			PackageInfo pinfo = context.getPackageManager().getPackageInfo(context.getPackageName(),
					PackageManager.GET_CONFIGURATIONS);
			versionCode = pinfo.versionCode;
		} catch (Exception e) {
		}
		return versionCode;
	}

	public static String getAppMetaData(Context context, String key) {
		String data = "";
		if ((context == null) || (TextUtils.isEmpty(key)))
			return data;
		try {
			PackageManager packageManager = context.getPackageManager();
			if (packageManager != null) {
				ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(),
						PackageManager.GET_META_DATA);
				if (applicationInfo != null && applicationInfo.metaData != null) {
					data = applicationInfo.metaData.get(key) + "";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return data;
		}
		return data;
	}

}
